//
//  NameListTableView.m
//  BOSS-SOOC
//
//  Created by apple on 16/8/31.
//  Copyright © 2016年 Gcx. All rights reserved.
//
#define REDCOLOR [self getColor:@"e86666"]

#import "NameListTableView.h"
#import "MMLabel.h"
#import "SC_TextFeild.h"
#import "NameListModel.h"
#import "XueshengTableViewCell.h"
#import "ClassManagerModel.h"

@interface SCTableView()<UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource>



@end

@implementation NameListTableView

- (id)initWithFrame:(CGRect)frame style:(UITableViewStyle)style{

    if (self = [super initWithFrame:frame style:style]) {
        
        self.dataSource = self;
        self.delegate = self;
        
        self.backgroundColor = BGC;
        
        self.separatorColor = colordbdbdb;
        
        self.orders = [NSMutableArray array];
        
        [self buildView];
        
        self.showEmpty = YES;
        
        [self emptyWithTitle:@"暂无订单" image:[UIImage imageNamed:@"空白页-搜索无数据图片"]];

        [self registerClass:[XueshengTableViewCell class] forCellReuseIdentifier:@"XueshengTableViewCell"];
    
        [self setupRefresh];
        
        [self.mj_header beginRefreshing];
    }
    return self;
}

- (void)setClassManagerModel:(ClassManagerModel *)classManagerModel{

    _classManagerModel = classManagerModel;
    
    NSLog(@"kcid == %@", _classManagerModel.kcid);
    
//    [self loadData:YES];
    
    self.listNum.text = [NSString stringWithFormat:@"名单人数：%@",_classManagerModel.xsrs];
    self.listNum.keyWord = _classManagerModel.xsrs;
    self.listNum.keyWordColor = [UIColor orangeColor];

}

- (void)buildView{

    self.myHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SIZEWIDTH, ScaleSize(270))];
    self.myHeaderView.backgroundColor = [UIColor whiteColor];
    
    self.listNum = [[MMLabel alloc]initWithFrame:CGRectMake(ScaleSize(42), 0, 150, ScaleSize(120))];
    self.listNum.text = @"名单人数：";
    self.listNum.keywords = @"名单人数：";
    self.listNum.font = NormalFont(42);
    self.listNum.textColor = Color333333;
    
    UIView *searchView = [[UIView alloc]initWithFrame:CGRectMake(ScaleSize(42), CGRectGetMaxY(self.listNum.frame)+ScaleSize(30), SIZEWIDTH - ScaleSize(86), ScaleSize(96))];
    searchView.layer.masksToBounds = YES;
    searchView.layer.cornerRadius = 3;
    searchView.layer.borderColor = colordbdbdb.CGColor;
    searchView.layer.borderWidth = 0.5;
    [self.myHeaderView addSubview:searchView];

    
    self.mySearchBar = [[SC_TextFeild alloc]initWithFrame:CGRectMake(0, 0, SIZEWIDTH - ScaleSize(186), ScaleSize(96))];
    [searchView addSubview:self.mySearchBar];
    self.mySearchBar.placeholder = @"姓名/学号/班级";
    
    UIView *shuxian = [[UIView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(self.mySearchBar.frame), ScaleSize(20), 0.5, ScaleSize(61))];
    shuxian.backgroundColor = colordbdbdb;
    [searchView addSubview:shuxian];
    
    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];

    addBtn.frame = CGRectMake(CGRectGetMaxX(shuxian.frame)+ScaleSize(27), ScaleSize(23), ScaleSize(50), ScaleSize(50));
    [addBtn setBackgroundImage:[UIImage imageNamed:@"搜索框内icon.png"] forState:UIControlStateNormal];
    [addBtn addTarget:self action:@selector(addBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    
    [self.myHeaderView addSubview:self.listNum];
    
    [searchView addSubview:addBtn];

    self.mySearchBar.backgroundColor = [UIColor whiteColor];
    self.mySearchBar.layer.masksToBounds = YES;
    self.mySearchBar.layer.cornerRadius = 3;
    self.mySearchBar.layer.borderColor = colordbdbdb.CGColor;
    self.mySearchBar.layer.borderWidth = 0.5;
    self.mySearchBar.layer.borderColor= [UIColor clearColor].CGColor;
    self.mySearchBar.returnKeyType = UIReturnKeySend;
    [self.mySearchBar setValue:colordbdbdb forKeyPath:@"_placeholderLabel.textColor"];
    [self.mySearchBar setValue:NormalFont(40) forKeyPath:@"_placeholderLabel.font"];
    self.mySearchBar.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.mySearchBar.font = NormalFont(42);
    
    self.mySearchBar.delegate = self;
    
    
    self.tableHeaderView = self.myHeaderView;

}

- (void)addBtnClicked{

    [self loadData:YES];
}

- (void)loadData:(BOOL)isRefresh{
    
    NSInteger pageIndex = 1;
    
    if (isRefresh) {
        
    } else {
    
        pageIndex = [self sc_currentPageNumWithTotalCount:self.orders.count];
    }

    NSMutableDictionary *parms = [[NSMutableDictionary alloc]init];
    [parms setObject:@"815bffb68e2ea44e38cf16a98a5a29a4" forKey:@"oauth_token"];
    [parms setObject:@"8e84bc64f03d73b5c75406ef1d7349f7" forKey:@"oauth_token_secret"];
    [parms setObject:@10 forKey:@"pageSize"];
    [parms setObject:_classManagerModel.kcid forKey:@"kcid"];
    [parms setObject:self.mySearchBar.text forKey:@"key"];
    [parms setValue:[NSMutableString stringWithFormat:@"%d", (int)pageIndex] forKey:@"pageNo"];
    
    SCHttpRequest *request = [[SCHttpRequest alloc]initWithApi:API_studentList params:parms];
    
    [self doPOSTConnect:request start:^(SCHttpRequest * _Nonnull req) {
        
    } success:^(SCHttpRequest * _Nonnull req, SCHttpResponse * _Nonnull resp) {
        
    
        NSLog(@"resp == %@", resp.originalDictionary);
    
        if ([resp.originalDictionary[@"status"]integerValue] == 0) {
            
            NSArray *arr  = resp.originalDictionary[@"data"][@"student"];
            
            NSArray<NameListModel*>*newArr = [NameListModel mj_objectArrayWithKeyValuesArray:arr];
            
            if (isRefresh) {
                
                [self.orders removeAllObjects];
            }
            
            [self.orders addObjectsFromArray:newArr];
            
            [self reloadData];

        } else {
            [[JLActionManager sharedInstance]showHUDWithLabelText:resp.originalDictionary[@"statusCode"] imageView:FailImage inView:self];
        }
        
        
    } failure:^(SCHttpRequest * _Nonnull req, NSError * _Nonnull error) {
        
    } finish:^(SCHttpRequest * _Nonnull req, BOOL success) {
        
        [self.mj_header endRefreshing];
        
//        [self.mj_footer endRefreshing];
    }];
}

- (void)reset{

    [self loadData:YES];
}

#pragma mark --

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.0001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.0001;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.orders.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 56.3;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *ident = @"cell";
    
    XueshengTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ident];
    
    if (!cell) {
        cell = [[NSBundle mainBundle]loadNibNamed:@"XueshengTableViewCell" owner:self options:nil][0];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    NameListModel* model = self.orders[indexPath.row];
    
    cell.nameLabel.text = [NSString stringWithFormat:@"%@（%@）", model.xm, model.xh];
    cell.xiahuaXianView.backgroundColor = colordbdbdb;
    cell.classLabel.text = [NSString stringWithFormat:@"%@", model.bj];
    
    cell.nameLabel.textColor = Color333333;
    cell.nameLabel.font = NormalFont(42);
    
    cell.classLabel.textColor = Color333333;
    cell.classLabel.font = NormalFont(42);
    
    return cell;
}

- (NSInteger)sc_currentPageNumWithTotalCount:(NSInteger)total{
    
    NSInteger _page_size = 10;
    
    NSInteger pindex = total / _page_size;
    
    //如果有余数, 则在上方除10的时候把余数丢掉.下方进行判断, 如果有余数, 则+1处理
    
    if (total % _page_size ) {
        
        pindex += 1;
    }
    return pindex+1;
    
}
/**
 *  刷新加载
 */
- (void)setupRefresh{
    
    //    __block __weak OptionTableView *table = self;
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        [self.mj_header beginRefreshing];
        
        [self loadData:YES];
        
    }];
    header.stateLabel.textColor = COLOR_TITLE_999999;
    header.lastUpdatedTimeLabel.textColor = COLOR_TITLE_999999;
    self.mj_header = header;
    

}

- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 添加一个删除按钮
    UITableViewRowAction *deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        
        NSLog(@"点击了删除");
        
        NameListModel *model = self.orders[indexPath.row];
        
        NSMutableDictionary *parms = [[NSMutableDictionary alloc]init];
        [parms setObject:@"815bffb68e2ea44e38cf16a98a5a29a4" forKey:@"oauth_token"];
        [parms setObject:@"8e84bc64f03d73b5c75406ef1d7349f7" forKey:@"oauth_token_secret"];
        [parms setObject:model.xh forKey:@"xh"];
        [parms setObject:_classManagerModel.kcid forKey:@"kcid"];
        
        SCHttpRequest *request = [[SCHttpRequest alloc]initWithApi:API_delStudent params:parms];
        
        [self doPOSTConnect:request start:^(SCHttpRequest * _Nonnull req) {
            
        } success:^(SCHttpRequest * _Nonnull req, SCHttpResponse * _Nonnull resp) {
            
            if ([resp.originalDictionary[@"status"]integerValue] == 0) {
                
                [self.orders removeObjectAtIndex:indexPath.row];
                // Delete the row from the data source.
                [self deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
                
            } else {
                
                [[JLActionManager sharedInstance]showHUDWithLabelText:resp.originalDictionary[@"statusCode"] imageView:FailImage inView:self];
            }
            
        } failure:^(SCHttpRequest * _Nonnull req, NSError * _Nonnull error) {
            
        } finish:^(SCHttpRequest * _Nonnull req, BOOL success) {
            
        }];
    }];

    deleteRowAction.backgroundColor = REDCOLOR;
    
    return @[deleteRowAction];
}
//时间戳转换

-(UIColor *)getColor:(NSString *)hexColor {
    unsigned int red,green,blue;
    NSRange range;
    range.length = 2;
    
    range.location = 0;
    [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&red];
    
    range.location = 2;
    [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&green];
    
    range.location = 4;
    [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&blue];
    
    return [UIColor colorWithRed:(float)(red/255.0f) green:(float)(green / 255.0f) blue:(float)(blue / 255.0f) alpha:1.0f];
}
@end
